<template>
    <div>
        <el-card>
            <!-- 顶部 搜索框 -->
            <el-input style="max-width: 20rem;margin-right: 1rem;" placeholder="请输入查询关键字" v-model="search" clearable>
                <template #prepend>
                    <el-button :icon="Search" />
                </template>
            </el-input>
            <el-button @click="openAddDialog">添加邮件</el-button>
            <!-- 表格 -->
            <el-table :data="filterMailList" :default-sort="{ prop: 'createdAt', order: 'descending' }" border
                style="width: 100%;margin-top: 1rem;">
                <el-table-column type="index" label="#" width="50" align="center" />
                <el-table-column prop="title" label="标题" width="130" show-overflow-tooltip />
                <el-table-column prop="senderName" label="发件人" width="100" show-overflow-tooltip />
                <el-table-column prop="content" label="内容" />
                <el-table-column prop="mailStatus" label="状态" width="70" align="center" :filters="[
                    { text: '未读', value: '未读' },
                    { text: '已读', value: '已读' },
                ]" :filter-method="filterTag" filter-placement="bottom-end">
                    <template #default="scope">
                        <el-tag :type="scope.row.mailStatus ? `success` : `warning`">{{ scope.row.mailStatus ? '已读' :
                            '未读'
                            }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" width="170" sortable :formatter="formatter"
                    align="center" />
                <el-table-column label="操作" width="180" align="center">
                    <template #default="scope">
                        <el-button type="primary" :icon="Edit" size="small" @click="editMail(scope.row)" />
                        <el-button type="success" :icon="Message" size="small" @click="seleArticle(scope.row.id)" />
                        <el-button type="danger" :icon="Delete" @click="deleteMail(scope.row.id)" size="small" />
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加/修改邮件对话框 -->
            <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" center @close="dialogClose">
                <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="auto" status-icon>
                    <el-form-item label="发件人" prop="senderName">
                        <el-input v-model="addForm.senderName" placeholder="请输入名称" />
                    </el-form-item>
                    <el-form-item label="标题">
                        <el-input v-model="addForm.title" placeholder="请输入标题" />
                    </el-form-item>
                    <el-form-item label="内容">
                        <el-input v-model="addForm.content" :rows="5" type="textarea" placeholder="请输入邮件内容"
                            show-word-limit maxlength="200" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="save(addFormRef)">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 选择物品奖励对话框 -->
            <el-dialog v-model="articleDialogVisible" title="选择物品" width="31%" center :show-close="false"
                :close-on-click-modal="false" :close-on-press-escape="false">
                <el-table :data="tableData" border style="width: 100%;margin-top: 1rem;" max-height="250"
                    @selection-change="handleSelectionChange" ref="multipleTableRef">
                    <el-table-column type="selection" width="50" />
                    <el-table-column prop="name" label="名称" width="150" />
                    <el-table-column prop="type" label="类型" width="80" align="center" :filters="[
                        { text: '武器', value: '武器' },
                        { text: '药水', value: '药水' },
                        { text: '道具', value: '道具' }
                    ]" :filter-method="filterTag" filter-placement="bottom-end">
                        <template #default="scope">
                            <el-tag :type="statusMap.get(scope.row.type)">{{ scope.row.type }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="date" label="数量" width="150" align="center">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.num" :precision="0" :min="0" size="small"
                                @change="changeNumber(scope.row)" />
                        </template>
                    </el-table-column>
                </el-table>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="articleDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="addPrizes">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { Search, Edit, Delete, Message } from '@element-plus/icons-vue'
import { ref, onMounted, nextTick, reactive, computed } from 'vue'
import { getArticleApi, addMailApi, getMailApi, delMailApi, addPrizesApi, updateMailApi } from "../api"
import type { articleType, mailType } from "../types"
import { ElMessage, ElTable, FormInstance } from 'element-plus';
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const addFormRef = ref<FormInstance>()
const dialogTitle = ref("添加邮件")
const search = ref("")
const dialogVisible = ref(false)
const articleDialogVisible = ref(false)
const addForm = reactive({
    id: 0,
    senderName: 'admin',
    content: '',
    title: '',
})
const restForm = ref({ ...addForm })
const mailList = ref<Array<mailType>>([])
const tableData = ref<Array<articleType>>([])
const prizes = ref<Array<articleType>>([])
const mailId = ref(0)
const statusMap = new Map([['武器', 'warning'], ['药水', 'success'], ['道具', 'danger']])
const addRules = ref({
    senderName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
})
onMounted(() => {
    getMailList()
})
const filterMailList = computed(() =>
    mailList.value.filter(
        (data) =>
            !search.value ||
            data.content.toLowerCase().includes(search.value.toLowerCase()) ||
            data.title.toLowerCase().includes(search.value.toLowerCase())
    )
)
// 选择奖励物品
const handleSelectionChange = (val: articleType[]) => {
    prizes.value = val
}
// 时间格式化
const formatter = (row: mailType) => {
    const date = new Date(row.createdAt as string);
    const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
    return formattedDate;
}
// 添加商品弹窗
const openAddDialog = () => {
    dialogVisible.value = true
    Object.assign(addForm, restForm.value)
}
// 选择物品奖励按钮
const seleArticle = (id: number) => {
    mailId.value = id
    articleDialogVisible.value = true
    getArticle(id)
}
// 获取所有物品
const getArticle = (id: number) => {
    getArticleApi().then(res => {
        res.data.forEach((item: articleType) => {
            mailList.value.forEach(i => {
                if (i.id === id) {
                    item.num = i.prizes?.find(j => item.id === j.articleId)?.num || 0
                }
            })
        })
        tableData.value = res.data
        tableData.value.forEach(item => {
            if (item.num !== 0) {
                nextTick(() => {
                    multipleTableRef.value?.toggleRowSelection(item, true)
                })
            }
        })
    })
}
// 获取邮件列表
const getMailList = () => {
    getMailApi().then(res => {
        mailList.value = res.data
    })
}
// tag类型筛选
const filterTag = (value: string, row: articleType) => {
    return row.type === value
}
// 添加邮件
const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            if (addForm.id) {
                let res = await updateMailApi(addForm)
                if (res.data.code === 200) {
                    ElMessage.success(res.data.msg)
                }
            }
            else {
                let res = await addMailApi(addForm)
                if (res.data.code === 200) {
                    ElMessage.success(res.data.msg)
                }
            }
            getMailList()
            dialogVisible.value = false
        } else {
            ElMessage.warning('请检查填写信息')
        }
    })
}
// 修改邮件
const editMail = (row: mailType) => {
    dialogTitle.value = '修改邮件'
    dialogVisible.value = true
    Object.assign(addForm, row)

}
// 删除邮件
const deleteMail = (id: number) => {
    delMailApi(id).then(res => {
        if (res.data.code === 200) {
            ElMessage.success(res.data.msg)
            getMailList()
        }
    })
}
// 添加奖励物品
const addPrizes = () => {
    prizes.value = prizes.value.filter(item => item.num !== 0)
    if (prizes.value.length === 0) { ElMessage.warning('请选择添加物品') }
    else addPrizesApi({ prizes: prizes.value, mailId: mailId.value }).then(res => {
        if (res.data.code === 200) {
            ElMessage.success(res.data.msg)
            articleDialogVisible.value = false
            getMailList()
        }
    })
}
// 选择奖品数量
const changeNumber = (row: articleType) => {
    if (row.num === 0) {
        multipleTableRef.value?.toggleRowSelection(row, false)
    } else {
        multipleTableRef.value?.toggleRowSelection(row, true)
    }
}
// 关闭对话框
const dialogClose = () => {
    addFormRef.value?.resetFields()
}
</script>

<style scoped></style>
